package com.gxc.controller;

import com.gxc.dto.Dept;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author GongXincheng
 * @since 2019-08-19 22:02
 */
@RestController
public class DeptController {

//    private static final String PROVIDER_URL_PREFIX = "http://localhost:8001";

    /** 加入 EurekaClient 依赖后，使用工程名称访问 provider 工程 */
    private static final String PROVIDER_URL_PREFIX = "http://SPRINGCLOUD-DEPT-PROVIDER-8001";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/test")
    public String hello() {
        return "Hello World !";
    }

    @GetMapping("/dept/{id}")
    public Dept findById(@PathVariable Long id) {
        Map<String, Long> map = new HashMap<>(1);
        map.put("id", id);
        return restTemplate.getForObject(PROVIDER_URL_PREFIX + "/dept/{id}", Dept.class, map);
    }

    @PostMapping("/dept")
    public Boolean add(@RequestBody Dept dept) {
        return restTemplate.postForObject(PROVIDER_URL_PREFIX + "/dept", dept, Boolean.class);
    }

    @GetMapping("/dept/list")
    public List<Dept> list() {
        ResponseEntity<List<Dept>> responseEntity = restTemplate.exchange(PROVIDER_URL_PREFIX + "/dept/list", HttpMethod.GET,
                null, new ParameterizedTypeReference<List<Dept>>() {
                });
        if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
            return responseEntity.getBody();
        }
        return null;
    }

    @GetMapping("/discovery")
    public Object discovery() {
        return restTemplate.getForObject(PROVIDER_URL_PREFIX+ "/discovery", Object.class);
    }
}
